﻿using DAL;
using IService;
using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Service
{
    public class SysOrganizationService : ISysOrganizationService
    {
        // 注入数据库上下文
        private readonly AppDbContext _dbContext;

        public SysOrganizationService(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task<List<SysOrganization>> GetOrgTreeAsync()
        {
            try
            {
                Console.WriteLine("开始获取组织机构树...");

                // 使用明确的列名选择，避免 EF Core 自动映射问题
                var allOrgs = await _dbContext.SysOrganization
                    .Where(o => o.OrgStatus == "启用")
                    .Select(o => new SysOrganization
                    {
                        OrgId = o.OrgId,
                        OrgCode = o.OrgCode,
                        OrgName = o.OrgName,
                        OrgShortName = o.OrgShortName,
                        ParentOrgId = o.ParentOrgId,
                        OrgLevel = o.OrgLevel,
                        OrgRemark = o.OrgRemark,
                        OrgStatus = o.OrgStatus
                        // Children 属性会在内存中构建，不从这里查询
                    })
                    .ToListAsync();

                Console.WriteLine($"查询到 {allOrgs.Count} 个启用的组织机构");

                // 构建树形结构
                var rootOrgs = allOrgs.Where(o => o.ParentOrgId == 0).ToList();
                Console.WriteLine($"找到 {rootOrgs.Count} 个根节点");

                foreach (var root in rootOrgs)
                {
                    BuildOrgTree(root, allOrgs);
                }

                Console.WriteLine("组织机构树构建完成");
                return rootOrgs;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取组织机构树异常: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                throw;
            }
        }

        private void BuildOrgTree(SysOrganization parent, List<SysOrganization> allOrgs)
        {
            var children = allOrgs.Where(o => o.ParentOrgId == parent.OrgId).ToList();
            if (children.Any())
            {
                parent.Children = children;
                foreach (var child in children)
                {
                    BuildOrgTree(child, allOrgs);
                }
            }
        }
        // 其他原有方法（保持不变）
        public async Task<List<SysOrganization>> GetAllAsync()
        {
            return await _dbContext.SysOrganization
            .Select(o => new SysOrganization
            {
                OrgId = o.OrgId,
                OrgCode = o.OrgCode,
                OrgName = o.OrgName,
                OrgLevel = o.OrgLevel,
                OrgStatus = o.OrgStatus
            })
            .OrderBy(o => o.OrgLevel)
            .ThenBy(o => o.OrgName)
            .ToListAsync();
        }

        public async Task<SysOrganization> GetByIdAsync(long id)
        {
            return await _dbContext.SysOrganization
                .FirstOrDefaultAsync(o => o.OrgId == id);
        }

        public async Task<bool> AddAsync(SysOrganization organization)
        {
            try
            {
                // 更严格的验证
                if (string.IsNullOrWhiteSpace(organization.OrgCode))
                {
                    Console.WriteLine("组织编号为空");
                    throw new ArgumentException("组织编号不能为空");
                }

                if (string.IsNullOrWhiteSpace(organization.OrgName))
                {
                    Console.WriteLine("组织名称为空");
                    throw new ArgumentException("组织名称不能为空");
                }

                if (organization.OrgLevel <= 0)
                {
                    Console.WriteLine("组织层级无效");
                    throw new ArgumentException("组织层级必须大于0");
                }

                // 设置默认值
                if (string.IsNullOrWhiteSpace(organization.OrgStatus))
                {
                    organization.OrgStatus = "启用";
                }

                // 确保 ParentOrgId 有合理值
                if (organization.ParentOrgId < 0)
                {
                    organization.ParentOrgId = 0;
                }
                // 新增：为orgShortName设置默认值（空字符串），避免NULL
                if (string.IsNullOrWhiteSpace(organization.OrgShortName))
                {
                    organization.OrgShortName = ""; // 空字符串而非NULL
                }
                // 检查组织编号是否已存在
                var existingOrg = await _dbContext.SysOrganization
                    .FirstOrDefaultAsync(o => o.OrgCode == organization.OrgCode);

                if (existingOrg != null)
                {
                    Console.WriteLine($"组织编号已存在: {organization.OrgCode}，现有组织名称: {existingOrg.OrgName}");
                    throw new ArgumentException($"组织编号 '{organization.OrgCode}' 已存在，请使用其他编号");
                }

                Console.WriteLine($"准备新增组织: OrgId={organization.OrgId}, OrgCode={organization.OrgCode}, " +
                                 $"OrgShortName={organization.OrgName}, ParentOrgId={organization.ParentOrgId}, " +
                                 $"OrgLevel={organization.OrgLevel}, OrgStatus={organization.OrgStatus}");

                // 添加到数据库
                _dbContext.SysOrganization.Add(organization);
                var result = await _dbContext.SaveChangesAsync();

                Console.WriteLine($"保存结果：{result} 行受影响，新组织ID: {organization.OrgId}");
                return result > 0;
            }
            catch (DbUpdateException dbEx)
            {
                Console.WriteLine($"数据库更新异常: {dbEx.Message}");
                if (dbEx.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {dbEx.InnerException.Message}");
                }
                throw; // 重新抛出异常，让控制器处理
            }
            catch (Exception ex)
            {
                Console.WriteLine($"新增组织异常: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                throw;
            }
        }
       public async Task<bool> UpdateAsync(SysOrganization organization)
{
    try
    {
        Console.WriteLine($"=== 开始更新组织 ===");
        Console.WriteLine($"更新数据: OrgId={organization.OrgId}, OrgCode={organization.OrgCode}, OrgShortName={organization.OrgName}");

        var existingOrg = await GetByIdAsync(organization.OrgId);
        if (existingOrg == null)
        {
            Console.WriteLine($"组织不存在: OrgId={organization.OrgId}");
            return false;
        }

        // 检查组织编号是否重复（排除自身）
        if (!string.IsNullOrWhiteSpace(organization.OrgCode))
        {
            var duplicateOrg = await _dbContext.SysOrganization
                .FirstOrDefaultAsync(o => o.OrgCode == organization.OrgCode && o.OrgId != organization.OrgId);
            
            if (duplicateOrg != null)
            {
                Console.WriteLine($"组织编号重复: {organization.OrgCode}，已存在组织: {duplicateOrg.OrgName}");
                throw new ArgumentException($"组织编号 '{organization.OrgCode}' 已存在，请使用其他编号");
            }
        }

        // 设置默认值
        if (string.IsNullOrWhiteSpace(organization.OrgShortName))
        {
            organization.OrgShortName = "";
        }

        Console.WriteLine($"准备更新组织: 原名称={existingOrg.OrgName}, 新名称={organization.OrgName}");

        // 使用 Attach 和 State 方式更新，避免跟踪冲突
        _dbContext.Entry(existingOrg).State = EntityState.Detached; // 先分离原有实体
        
        _dbContext.SysOrganization.Attach(organization);
        _dbContext.Entry(organization).State = EntityState.Modified;

        var result = await _dbContext.SaveChangesAsync();
        
        Console.WriteLine($"更新结果: {result} 行受影响");
        return result > 0;
    }
    catch (DbUpdateException dbEx)
    {
        Console.WriteLine($"数据库更新异常: {dbEx.Message}");
        if (dbEx.InnerException != null)
        {
            Console.WriteLine($"内部异常: {dbEx.InnerException.Message}");
        }
        throw;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"更新组织异常: {ex.Message}");
        Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
        throw;
    }
}

        public async Task<bool> DeleteAsync(long id)
        {
            var org = await GetByIdAsync(id);
            if (org == null)
            {
                return false;
            }

            _dbContext.SysOrganization.Remove(org);
            return await _dbContext.SaveChangesAsync() > 0;
        }

        public async Task<bool> BatchDeleteAsync(List<long> ids)
        {
            if (ids == null || !ids.Any())
            {
                return false;
            }

            var orgsToDelete = await _dbContext.SysOrganization
                .Where(o => ids.Contains(o.OrgId))
                .ToListAsync();

            if (!orgsToDelete.Any())
            {
                return false;
            }

            _dbContext.SysOrganization.RemoveRange(orgsToDelete);
            return await _dbContext.SaveChangesAsync() > 0;
        }

        public async Task<List<SysOrganization>> QueryAsync(string keyword, string status)
        {
            var query = _dbContext.SysOrganization.AsQueryable();

            // 映射编码为状态名称
            if (status == "0") status = "启用";
            if (status == "1") status = "停用";

            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(o =>
                    o.OrgName.Contains(keyword) ||
                    o.OrgCode.Contains(keyword)
                );
            }

            if (!string.IsNullOrEmpty(status))
            {
                query = query.Where(o => o.OrgStatus == status);
            }

            return await query
                .OrderBy(o => o.OrgLevel)
                .ThenBy(o => o.OrgName)
                .ToListAsync();
        }


        // 【修改重点】组织编号生成方法（异步化并完善逻辑）
        /// <summary>
        /// 生成组织编号（前缀+3位自增序号，如FTJG001）
        /// </summary>
        /// <param name="prefix">编号前缀（如"FTJG"、"CG"）</param>
        /// <returns>生成的唯一编号</returns>
        public async Task<string> GenerateOrgCodeAsync(string prefix)
        {
            // 1. 验证前缀合法性
            if (string.IsNullOrWhiteSpace(prefix))
                throw new ArgumentException("组织编号前缀不能为空", nameof(prefix));

            // 2. 异步查询数据库中该前缀的最大编号
            var maxCode = await _dbContext.SysOrganization
                .Where(o => o.OrgCode != null && o.OrgCode.StartsWith(prefix)) // 过滤有效数据
                .OrderByDescending(o => o.OrgCode) // 按编号降序，取最大的
                .Select(o => o.OrgCode)
                .FirstOrDefaultAsync(); // 异步查询

            // 3. 生成新编号
            if (string.IsNullOrEmpty(maxCode))
            {
                // 无前缀数据时，从001开始
                return $"{prefix}001";
            }

            // 提取序号部分（前缀后的数字）
            string numberPart = maxCode.Substring(prefix.Length);
            if (int.TryParse(numberPart, out int currentNumber))
            {
                // 序号+1并格式化为3位补零（如001、002）
                return $"{prefix}{(currentNumber + 1):D3}";
            }
            else
            {
                // 序号解析失败（如格式不符合预期），默认从001开始
                return $"{prefix}001";
            }
        }

        public async Task<bool> CheckCodeExistsAsync(string code)
        {
            if (string.IsNullOrEmpty(code))
                return false;

            var existingOrg = await _dbContext.SysOrganization
                .FirstOrDefaultAsync(o => o.OrgCode == code);

            return existingOrg != null;
        }
    }
}